import url from './url'
import request from './request'
import URI from 'urijs'
import store from 'store'
import { aliyun } from './config'

const base     = url.base,
      loginOut = request.loginOut

let getUrlParam = function (name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  let r   = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2]);
  return null
}

let catchError = function (res) {

  let status = res[1]

  if (status === 'error') {

    let jqXHR = res[0],
        code  = jqXHR.status

    // 502 和 505表示系统维护
    if (code === 502 || code === 505) {
      window.location = 'maintenance.html'

      return
    }

    // const err = layer.msg('无访问权限，将跳转到登录页面', {
    //   icon: 5
    // })

    //询问框

    const hasError = layer.confirm('无访问权限，是否跳转到登录页面？', {
      btn: ['是', '否'] //按钮
    }, function () {
      quit()
    }, function () {
      layer.close(hasError)
    })

    // store.set('error', res)
    // quit()

    return

  }

  if (status === 'success') {
    let jqXHR = res[0]

    if (jqXHR.code === -1) {
      let error = Number(jqXHR.error)

      switch (error) {
        case 403:
          // layer.msg(jqXHR.message || '无访问权限，将跳转到登录页面', {
          //   icon: 5
          // })
          //
          // quit()
          const hasError = layer.confirm('无访问权限，是否跳转到登录页面？', {
            btn: ['是', '否'] //按钮
          }, function () {
            quit()
          }, function () {
            layer.close(hasError)
          })

          break
      }

    }
  }

}

let quit = function () {
  // 清除认证
  Cookies.remove('myToken', { path: '/' })
  // 清楚本地缓存
  store.clearAll()

  setTimeout(() => {
    // window.location = window.origin + '/' + 'login.html'
    window.location = window.origin
  }, 500)
}

let isIp = function (text) {
  let regex = new RegExp("^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +
    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$");

  return regex.test(text)
}

let toIndex = function () {
  let menuToggle = '',
      i          = 0,
      len        = window.menu.menus.length

  for (; i < len; i++) {
    menuToggle += (window.menu.menus[i].active ? '1' : '0')
  }

  setTimeout(() => {
    window.location = new URI('./index.html', window.location.href).toString()
  }, 1000)
}

function isObject (obj) {
  return Object.prototype.toString.call(obj) === '[object Object]' ? true : false
}

function random_string (len) {
  len        = len || 32
  let chars  = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
      maxPos = chars.length,
      pwd    = '',
      i      = 0

  for (; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }

  return pwd
}

function get_suffix (filename) {
  let pos    = filename.lastIndexOf('.'),
      suffix = ''

  if (pos !== -1) {
    suffix = filename.substring(pos)
  }

  return suffix
}

// 预览阿里云图片
function previewImg (key, config) {
  config = config || {}

  if (typeof key !== 'string' && !key.length) {
    return
  }

  let client = new OSS.Wrapper({
    secure: true,
    region: aliyun.region,
    accessKeyId: aliyun.accessKeyId,
    accessKeySecret: aliyun.accessKeySecret,
    bucket: aliyun.bucket
  })

  return client.signatureUrl(key, config)

}

// 模态预览图片
function imgPreviewModal (url) {

  if (typeof url !== 'string' && !url.length) {
    return
  }

  let $img = $('<img>').css({
    width: '100%'
  })

  $img.on('load', function () {

    bootbox.alert({
      title: '图片预览',
      message: $img
    })

  }).on('error', function () {
    layer.msg('图片预览失败', {
      icon: 5
    })
  }).attr('src', url)

}

function fetch ({ url, data }) {
  return $.ajax({
    type: "POST",
    url: base + url,
    dataType: "json",
    data: data,
    headers: {
      myToken: Cookies.get('myToken')
    },
  })
}

function fetch2 (url, data) {
  return $.ajax({
    type: "POST",
    url: base + url,
    dataType: "json",
    data: data,
    headers: {
      myToken: Cookies.get('myToken')
    },
  })
}

export {
  getUrlParam,
  catchError,
  isIp,
  toIndex,
  quit,
  isObject,
  random_string,
  get_suffix,
  previewImg,
  imgPreviewModal,
  fetch,
  fetch2
}